package com.huluobo.kotlindemoim1911a2.contract.chat

import android.util.Log
import com.huluobo.kotlindemoim1911a2.adapter.EMCallbackAdapter
import com.hyphenate.chat.EMClient
import com.hyphenate.chat.EMMessage
import org.jetbrains.anko.doAsync

/**
 * Created by lc on 2022/10/28.
 */
class ChatPresenter(private val view: ChatContract.View) : ChatContract.Presenter {
    companion object {
        const val PAGE_SIZE = 10
    }

    val messages = mutableListOf<EMMessage>()
    override fun sendMessage(contact: String, message: String) {
        //构建一条消息
        val emMessage = EMMessage.createTxtSendMessage(message, contact)
        emMessage.setMessageStatusCallback(object : EMCallbackAdapter() {
            override fun onSuccess() {
                runOnUIThread {
                    view.onSendMessageSuccess()
                }
            }

            override fun onError(code: Int, error: String?) {
                runOnUIThread {
                    view.onSendMessageFailed()
                }
                Log.i("TagA", "setMessageStatusCallback:$code,error:$error")
            }
        })
        messages.add(emMessage)
        view.onStartSendMessage()
        EMClient.getInstance().chatManager().sendMessage(emMessage)
    }

    override fun addMessage(username: String, messages: MutableList<EMMessage>?) {
        //加入到当前的消息列表
        messages?.let {
            this.messages.addAll(it)
        }

        //更新消息状态为已读
        val conversation = EMClient.getInstance().chatManager().getConversation(username)
        conversation.markAllMessagesAsRead()
    }

    override fun loadMessages(username: String) {
        doAsync {
            val conversation = EMClient.getInstance().chatManager().getConversation(username)
            conversation.markAllMessagesAsRead()
            messages.addAll(conversation.allMessages)
            runOnUIThread {
                view.onMessagesLoaded()
            }
        }
    }

    override fun loadMoreMessage(username: String) {
        doAsync {
            val conversation = EMClient.getInstance().chatManager().getConversation(username)
            val startMsgId = messages[0].msgId//查询历史聊天记录的起始位置
            val loadMoreFromDB = conversation.loadMoreMsgFromDB(startMsgId, PAGE_SIZE)
            messages.addAll(0, loadMoreFromDB)//加载历史聊天记录时,不能从list的尾部进行添加,需要从list的头部进行添加
            runOnUIThread {
                view.onMoreMessagesLoaded(loadMoreFromDB.size)
            }
        }
    }
}